package com.clinic.logic.drugIssue;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.clinic.accessor.db.DrugAccessor;
import com.clinic.accessor.db.DrugStockAccessor;
import com.clinic.accessor.db.PrescriptionAccessor;
import com.clinic.entity.db.Drug;
import com.clinic.entity.db.DrugIssue;
import com.clinic.entity.db.DrugStock;
import com.clinic.entity.db.Prescription;
import com.clinic.entity.gui.GuiDrugIssue;
import com.clinic.entity.param.Index;

@Component
public class DrugIssueLogic {

	@Autowired
	private PrescriptionAccessor prescriptionAccessor;
	@Autowired
	private DrugAccessor drugAccessor;
	@Autowired
	private DrugStockAccessor drugStockAccessor;
	
	@Transactional
	public void updatePrescriptionDrugIssueList(long prescriptionId, List<GuiDrugIssue> guiDrugIssueList) {
		Prescription prescription = prescriptionAccessor.getPrescriptionById(prescriptionId);
		if (prescription != null) {
			Set<DrugIssue> drugIssues = prescription.getIssues();
			for (DrugIssue drugIssue : drugIssues) {
				for (GuiDrugIssue guiDrugIssue : guiDrugIssueList) {
					if (guiDrugIssue != null && guiDrugIssue.getDrugIssueId() == drugIssue.getDrugIssueId()) {
						drugIssue.setIssue(guiDrugIssue.isIssue());
						
						if (guiDrugIssue.isIssue()) {
							Drug drug = drugAccessor.getDrugById(guiDrugIssue.getDrug().getDrugId());
							drugIssue.setDrug(drug);
							int recommandedDrugsAmount = drugIssue.getNoOfDays() * drugIssue.getTermsPerDay();
							int waitingDrugsAmount = recommandedDrugsAmount; // drugs to be issue from stocks
							List<DrugStock> drugStockList = drugStockAccessor.getAvailableDrugStocksByDrugId(drug.getDrugId(), new Index());
							for (DrugStock drugStock : drugStockList) {
								int availableDrugsAmount = drugStock.getStockAmount();
								if (availableDrugsAmount >= waitingDrugsAmount) {
									drugStock.setStockAmount(availableDrugsAmount - recommandedDrugsAmount);
									waitingDrugsAmount = 0;
								} else if (availableDrugsAmount < recommandedDrugsAmount && availableDrugsAmount > 0) {
									waitingDrugsAmount = waitingDrugsAmount - availableDrugsAmount;
									drugStock.setStockAmount(0);
								}
								if (waitingDrugsAmount == 0) {
									break;
								}
							}
							drugIssue.setDrugStocks(new HashSet<>(drugStockList));
						}
					}
				}
			}
			prescriptionAccessor.insertOrUpdate(prescription);
		}
	}
	
}
